package com.approval.approvalapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.approval.approval.ClassBean;
import com.approval.approvalapp.bean.GxBean;
import com.approval.approvalapp.center.centerfragment.CenterMySelfFragment;
import com.approval.approvalapp.center.index.CenterIndexFragment;
import com.approval.approvalapp.index.IndexFragment;
import com.approval.approvalapp.index.dbsx.tshf.BaseActivity2;
import com.approval.approvalapp.knowledge.KnowladgeFragment;
import com.approval.approvalapp.message.MessageFragment;
import com.approval.approvalapp.myself.MyselfFragment;
import com.approval.approvalapp.util.DensityUtil;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.base.BaseActivity;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.DownResponseInterface;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity {

    @Bind(R.id.iv1)
    ImageView iv1;
    @Bind(R.id.iv2)
    ImageView iv2;
    @Bind(R.id.iv3)
    ImageView iv3;
    @Bind(R.id.iv4)
    ImageView iv4;
    @Bind(R.id.bottom_ll)
    LinearLayout bottomLl;
    @Bind(R.id.replaceView)
    FrameLayout replaceView;
    @Bind(R.id.tv1)
    TextView tv1;
    @Bind(R.id.ll1)
    LinearLayout ll1;
    @Bind(R.id.tv2)
    TextView tv2;
    @Bind(R.id.ll2)
    LinearLayout ll2;
    @Bind(R.id.tv3)
    TextView tv3;
    @Bind(R.id.ll3)
    LinearLayout ll3;
    @Bind(R.id.tv4)
    TextView tv4;
    @Bind(R.id.ll4)
    LinearLayout ll4;
    @Bind(R.id.tip_tv_2)
    TextView tipTv2;
    @Bind(R.id.tip_rl_2)
    RelativeLayout tipRl2;
    private FragmentManager fragmentManager;
    private int currentBottomPosition;
    private int targetBottomPosition;
    private List<Fragment> fragmentList;
    private static MainActivity instance;
    private int REQUEST_CODE_UNKNOWN_APP = 100;
    private String down_url;
    private ProgressDialog progressDialog;


    @Override
    public int getLayoutId() {
        instance = this;
        return R.layout.activity_main;
    }

    public static MainActivity getInstance() {
        return instance;
    }

    @Override
    public void initView() {
        int statusBarHeight = DensityUtil.getStatusBarHeight(this);


        fragmentList = new ArrayList<>();
        if (SpUtil.getString(this,SpUtil.Usertype,"").equals("1")){
            fragmentList.add(new CenterIndexFragment());//中心端首页(1)
            fragmentList.add(new MessageFragment());
            fragmentList.add(new KnowladgeFragment());
            fragmentList.add(new CenterMySelfFragment());
            fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().add(R.id.replaceView, fragmentList.get(0)).commit();
        }else {
            fragmentList.add(new IndexFragment());//2,3
            fragmentList.add(new MessageFragment());
            fragmentList.add(new KnowladgeFragment());
            fragmentList.add(new MyselfFragment());
            fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().add(R.id.replaceView, fragmentList.get(0)).commit();
        }



    }

    @Override
    public void initData() {
        getVersion();

        NetRequsetUtil.getInstance().netRequestGet("v1/user/get_android_update", new NetDownResponse() {
            @Override
            public void success(String str) {
                GxBean gxBean = JSON.parseObject(str, GxBean.class);
                String version = gxBean.getVersion();
                down_url = gxBean.getDown_url();
                if (Integer.valueOf(version) > getVersion()) {
                    //更新
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
                        if (hasInstallPermission) {
                            //安装应用
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("有新版本请更新").setNegativeButton("更新", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startDownload(down_url);
                                }
                            });
                            builder.show();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setMessage("8,0系统以上更新需要获取安装未知应用权限").setNegativeButton("获取", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //跳转至“安装未知应用”权限界面，引导用户开启权限
                                    Uri selfPackageUri = Uri.parse("package:" + MainActivity.this.getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, selfPackageUri);
                                    startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP);
                                }
                            });
                            builder.show();
                        }
                    }else {
                        //安装应用
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage("有新版本请更新").setNegativeButton("更新", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startDownload(down_url);
                            }
                        });
                        builder.show();
                    }

                }
            }

            @Override
            public void errowithresponse(String str) {

            }

            @Override
            public void erro() {

            }

            @Override
            public void finish() {

            }
        });

        getNotice();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getNotice();

        NetRequsetUtil.getInstance().netRequestGet2("http://testapp.ciotimes.com/CIO.api/api/v2/user/is_use_grfw",
                new NetDownResponse() {
                    @Override
                    public void success(String str) {
                    }

                    @Override
                    public void errowithresponse(String str) {
                        System.exit(0);
                    }

                    @Override
                    public void erro() {

                    }

                    @Override
                    public void finish() {

                    }
                });
    }

    public void getNotice() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("org_code", SpUtil.getString(this,SpUtil.ORG_CODE,""));
        NetRequsetUtil.getInstance().netRequestPostJson("v1/user/get_notice_num",jsonObject.toJSONString(), new NetDownResponse() {
            @Override
            public void success(String str) {
                //最下方tab第二个消息红点
                ClassBean classBean = JSON.parseObject(str, ClassBean.class);
                if (classBean.getNum() == 0) {
                    MainActivity.getInstance().refreshNotice(0);
                } else {
                    MainActivity.getInstance().refreshNotice(classBean.getNum());
                }
            }

            @Override
            public void errowithresponse(String str) {

            }

            @Override
            public void erro() {

            }

            @Override
            public void finish() {

            }
        });
    }



    @OnClick({R.id.ll1, R.id.ll2, R.id.ll3, R.id.ll4})
    public void onViewClicked(View view) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        switch (view.getId()) {
            case R.id.ll1:
                setAndroidNativeLightStatusBar(this,false);
                targetBottomPosition = 0;
                if (currentBottomPosition == 0) {
                    return;
                }
                fragmentTransaction.hide(fragmentList.get(currentBottomPosition));
                if (!fragmentList.get(targetBottomPosition).isAdded()) {
                    fragmentTransaction.add(R.id.replaceView, fragmentList.get(targetBottomPosition));
                }
                fragmentTransaction.show(fragmentList.get(targetBottomPosition)).commit();
                currentBottomPosition = 0;
                iv1.setImageResource(R.drawable.list_click);
                iv2.setImageResource(R.drawable.information);
                iv3.setImageResource(R.drawable.data);
                iv4.setImageResource(R.drawable.mine);
                tv1.setTextColor(Color.parseColor("#1465FD"));
                tv2.setTextColor(Color.parseColor("#000000"));
                tv3.setTextColor(Color.parseColor("#000000"));
                tv4.setTextColor(Color.parseColor("#000000"));
                break;
            case R.id.ll2:
                setAndroidNativeLightStatusBar(this,false);

                targetBottomPosition = 1;
                if (currentBottomPosition == 1) {
                    return;
                }
                fragmentTransaction.hide(fragmentList.get(currentBottomPosition));
                if (!fragmentList.get(targetBottomPosition).isAdded()) {
                    fragmentTransaction.add(R.id.replaceView, fragmentList.get(targetBottomPosition));
                }
                fragmentTransaction.show(fragmentList.get(targetBottomPosition)).commit();
                currentBottomPosition = 1;
                iv1.setImageResource(R.drawable.list);
                iv2.setImageResource(R.drawable.information_click);
                iv3.setImageResource(R.drawable.data);
                iv4.setImageResource(R.drawable.mine);
                tv1.setTextColor(Color.parseColor("#000000"));
                tv2.setTextColor(Color.parseColor("#1465FD"));
                tv3.setTextColor(Color.parseColor("#000000"));
                tv4.setTextColor(Color.parseColor("#000000"));
                break;
            case R.id.ll3:
                setAndroidNativeLightStatusBar(this,false);

                targetBottomPosition = 2;
                if (currentBottomPosition == 2) {
                    return;
                }
                fragmentTransaction.hide(fragmentList.get(currentBottomPosition));
                if (!fragmentList.get(targetBottomPosition).isAdded()) {
                    fragmentTransaction.add(R.id.replaceView, fragmentList.get(targetBottomPosition));
                }
                fragmentTransaction.show(fragmentList.get(targetBottomPosition)).commit();
                currentBottomPosition = 2;
                iv1.setImageResource(R.drawable.list);
                iv2.setImageResource(R.drawable.information);
                iv3.setImageResource(R.drawable.data_click);
                iv4.setImageResource(R.drawable.mine);
                tv1.setTextColor(Color.parseColor("#000000"));
                tv2.setTextColor(Color.parseColor("#000000"));
                tv3.setTextColor(Color.parseColor("#1465FD"));
                tv4.setTextColor(Color.parseColor("#000000"));
                break;
            case R.id.ll4:
                setAndroidNativeLightStatusBar(this,false);
                targetBottomPosition = 3;
                if (currentBottomPosition == 3) {
                    return;
                }
                fragmentTransaction.hide(fragmentList.get(currentBottomPosition));
                if (!fragmentList.get(targetBottomPosition).isAdded()) {
                    fragmentTransaction.add(R.id.replaceView, fragmentList.get(targetBottomPosition));
                }
                fragmentTransaction.show(fragmentList.get(targetBottomPosition)).commit();
                currentBottomPosition = 3;
                iv1.setImageResource(R.drawable.list);
                iv2.setImageResource(R.drawable.information);
                iv3.setImageResource(R.drawable.data);
                iv4.setImageResource(R.drawable.mine_click);
                tv1.setTextColor(Color.parseColor("#000000"));
                tv2.setTextColor(Color.parseColor("#000000"));
                tv3.setTextColor(Color.parseColor("#000000"));
                tv4.setTextColor(Color.parseColor("#1465FD"));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_UNKNOWN_APP) {
            //安装应用
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("有新版本请更新").setNegativeButton("更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                   startDownload(down_url);
                }
            });
            builder.show();
        }
    }

    private void startDownload(String down_url) {
        //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setProgressNumberFormat(" ");
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        NetRequsetUtil.getInstance().upApk(down_url, "grfw.apk", new DownResponseInterface() {
            @Override
            public void successFinish() {
                progressDialog.dismiss();
                //Android获取一个用于打开APK文件的intent
                Intent intent1 = new Intent(Intent.ACTION_VIEW);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
                    //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                    File file = new File(Environment.getExternalStorageDirectory(), "grfw.apk");
                    if (file.exists()){
                        Log.d("MainActivitysss", file.getAbsolutePath());
                    }
                    Uri apkUri =
                            FileProvider.getUriForFile(MainActivity.this,
                                    "com.approval.approvalapp.fileprovider",
                                    file);
                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                    intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent1.setDataAndType(apkUri, "application/vnd.android.package-archive");
                }else{
                    intent1.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"grfw.apk")),
                            "application/vnd.android.package-archive");
                }
                MainActivity.this.startActivity(intent1);
            }

            @Override
            public void progress(int progress) {
                Log.d("MainAcprogress", "progress:" + progress);
                progressDialog.setProgress(progress);

            }

            @Override
            public void erro() {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void refreshNotice(int num) {
        if (num == 0) {
            tipRl2.setVisibility(View.GONE);
        } else {
            tipRl2.setVisibility(View.VISIBLE);
            if (num < 99) {
                tipTv2.setText(num + "");
            } else {
                tipTv2.setText(99 + "");
            }
        }
    }


    private int getVersion() {
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = null;
            try {
                packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetRequsetUtil.setEnd(true);
    }
}
